#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
查询真实的HAI信息
"""

import os
import sys
import json
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

# 加载环境变量
from dotenv import load_dotenv
load_dotenv()

def query_hai_capabilities():
    """查询HAI服务能力"""
    print("🔍 查询HAI服务能力")
    print("=" * 50)
    
    try:
        from tencentcloud.common import credential
        from tencentcloud.hai.v20230812 import hai_client, models
        from tencentcloud.common.profile.client_profile import ClientProfile
        from tencentcloud.common.profile.http_profile import HttpProfile
        
        # 创建凭证
        cred = credential.Credential(
            os.getenv('TENCENT_SECRET_ID'),
            os.getenv('TENCENT_SECRET_KEY')
        )
        
        # 创建客户端
        profile = ClientProfile()
        profile.httpProfile = HttpProfile()
        profile.httpProfile.endpoint = "hai.tencentcloudapi.com"
        
        client = hai_client.HaiClient(cred, "ap-beijing", profile)
        
        print("✅ HAI客户端创建成功")
        
        # 查询可用地域
        print("\n🌍 查询可用地域...")
        try:
            req = models.DescribeRegionsRequest()
            resp = client.DescribeRegions(req)
            
            print(f"✅ 地域查询成功:")
            if hasattr(resp, 'RegionSet') and resp.RegionSet:
                for region in resp.RegionSet:
                    print(f"  - {region.Region}: {region.RegionName} ({region.RegionState})")
            else:
                print("  ❌ 没有可用地域")
                
        except Exception as e:
            print(f"❌ 地域查询失败: {e}")
        
        # 查询应用信息
        print("\n📱 查询应用信息...")
        try:
            req = models.DescribeApplicationsRequest()
            resp = client.DescribeApplications(req)
            
            print(f"✅ 应用查询成功:")
            if hasattr(resp, 'ApplicationSet') and resp.ApplicationSet:
                for app in resp.ApplicationSet:
                    print(f"  - {app.ApplicationId}: {app.ApplicationName}")
                    print(f"    状态: {app.ApplicationState}")
                    print(f"    地域: {app.Region}")
                    print(f"    创建时间: {app.CreatedTime}")
                    print()
            else:
                print("  ❌ 没有可用应用")
                
        except Exception as e:
            print(f"❌ 应用查询失败: {e}")
        
        # 查询实例类型
        print("\n🖥️ 查询实例类型...")
        try:
            # 尝试不同的查询方法
            req = models.DescribeInstanceTypesRequest()
            resp = client.DescribeInstanceTypes(req)
            
            print(f"✅ 实例类型查询成功:")
            if hasattr(resp, 'InstanceTypeSet') and resp.InstanceTypeSet:
                for instance_type in resp.InstanceTypeSet:
                    print(f"  - {instance_type.InstanceType}")
                    print(f"    CPU: {instance_type.CPU}")
                    print(f"    内存: {instance_type.Memory}")
                    print(f"    GPU: {instance_type.GPU}")
                    print(f"    GPU类型: {instance_type.GPUType}")
                    print()
            else:
                print("  ❌ 没有可用实例类型")
                
        except Exception as e:
            print(f"❌ 实例类型查询失败: {e}")
        
        # 查询现有实例
        print("\n📋 查询现有实例...")
        try:
            req = models.DescribeInstancesRequest()
            resp = client.DescribeInstances(req)
            
            print(f"✅ 实例查询成功:")
            if hasattr(resp, 'InstanceSet') and resp.InstanceSet:
                for instance in resp.InstanceSet:
                    print(f"  - {instance.InstanceId}: {instance.InstanceName}")
                    print(f"    状态: {instance.InstanceState}")
                    print(f"    应用: {instance.ApplicationId}")
                    print(f"    地域: {instance.Region}")
                    print(f"    创建时间: {instance.CreatedTime}")
                    print()
            else:
                print("  ❌ 没有现有实例")
                
        except Exception as e:
            print(f"❌ 实例查询失败: {e}")
        
        return True
        
    except Exception as e:
        print(f"❌ 查询失败: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_create_instance_with_minimal_params():
    """使用最小参数测试创建实例"""
    print("\n🧪 测试创建实例（最小参数）")
    print("=" * 50)
    
    try:
        from tencentcloud.common import credential
        from tencentcloud.hai.v20230812 import hai_client, models
        from tencentcloud.common.profile.client_profile import ClientProfile
        from tencentcloud.common.profile.http_profile import HttpProfile
        
        # 创建凭证
        cred = credential.Credential(
            os.getenv('TENCENT_SECRET_ID'),
            os.getenv('TENCENT_SECRET_KEY')
        )
        
        # 创建客户端
        profile = ClientProfile()
        profile.httpProfile = HttpProfile()
        profile.httpProfile.endpoint = "hai.tencentcloudapi.com"
        
        client = hai_client.HaiClient(cred, "ap-beijing", profile)
        
        # 创建实例请求
        req = models.RunInstancesRequest()
        
        # 只设置必需参数
        req.ApplicationId = "app-oefac6i2"
        req.InstanceName = "test-minimal-instance"
        req.InstanceCount = 1
        
        print(f"📋 测试参数:")
        print(f"  ApplicationId: {req.ApplicationId}")
        print(f"  InstanceName: {req.InstanceName}")
        print(f"  InstanceCount: {req.InstanceCount}")
        
        # 不设置BundleType，让系统自动选择
        print(f"  BundleType: 未设置（让系统自动选择）")
        
        # 执行创建实例
        print(f"\n🚀 开始创建实例...")
        resp = client.RunInstances(req)
        
        print(f"✅ 实例创建成功!")
        print(f"请求ID: {resp.RequestId}")
        
        if hasattr(resp, 'InstanceIdSet') and resp.InstanceIdSet:
            instance_ids = resp.InstanceIdSet
            print(f"实例ID列表: {instance_ids}")
            
            for instance_id in instance_ids:
                print(f"\n📊 实例详情:")
                print(f"  实例ID: {instance_id}")
                print(f"  应用ID: {req.ApplicationId}")
                print(f"  实例名称: {req.InstanceName}")
                print(f"  地域: ap-beijing")
            
            return instance_ids[0] if instance_ids else None
        else:
            print("❌ 未返回实例ID")
            return None
            
    except Exception as e:
        print(f"❌ 创建实例失败: {e}")
        
        # 分析错误信息
        error_msg = str(e)
        if "BundleType" in error_msg:
            print(f"\n💡 错误分析: 缺少BundleType参数")
            print(f"建议: 需要提供正确的BundleType")
        elif "ApplicationId" in error_msg:
            print(f"\n💡 错误分析: ApplicationId无效")
            print(f"建议: 检查应用ID是否正确")
        elif "Permission" in error_msg or "权限" in error_msg:
            print(f"\n💡 错误分析: 权限不足")
            print(f"建议: 检查子账号权限")
        elif "Quota" in error_msg or "配额" in error_msg:
            print(f"\n💡 错误分析: 配额不足")
            print(f"建议: 检查实例配额")
        
        return None

def main():
    """主函数"""
    print("🚀 查询真实HAI信息")
    print("=" * 60)
    
    # 检查环境变量
    secret_id = os.getenv('TENCENT_SECRET_ID')
    secret_key = os.getenv('TENCENT_SECRET_KEY')
    
    if not secret_id or not secret_key:
        print("❌ 环境变量未配置")
        return False
    
    print(f"Secret ID: {secret_id[:10]}...")
    print(f"Secret Key: {secret_key[:10]}...")
    
    # 查询HAI服务能力
    if query_hai_capabilities():
        print("\n✅ HAI服务能力查询完成")
    else:
        print("\n❌ HAI服务能力查询失败")
        return False
    
    # 测试创建实例
    instance_id = test_create_instance_with_minimal_params()
    
    if instance_id:
        print(f"\n🎉 真实HAI实例创建成功！")
        print(f"实例ID: {instance_id}")
        return True
    else:
        print(f"\n❌ 真实实例创建失败")
        
        print(f"\n📋 需要的信息:")
        print(f"1. 正确的BundleType")
        print(f"2. 确认应用ID是否正确")
        print(f"3. 确认权限配置")
        print(f"4. 确认配额情况")
        
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
